<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>小程序蓝牙记录 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="小程序,蓝牙,">
  

  <meta name="description" content="一、背景介绍 蓝牙是爱立信公司创立的一种无线技术标准，为短距离的硬件设备提供低成本的通信规范。蓝牙规范由蓝牙技术联盟（Bluetooth Special Interest Group，简称SIG）管理，在计算机，手机，传真机，耳机，汽车，家用电器等等很多场景广泛使用。蓝牙具有以下一些特点   免费使用：使用的工作频段在2.4GHz的工科医（ISM）频段，无需申请许可证。 功耗低：BLE4.0包含了">
<meta name="keywords" content="小程序,蓝牙">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序蓝牙记录">
<meta property="og:url" content="http://blog.poetries.top/2019/08/31/weapp-bluetooth/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、背景介绍 蓝牙是爱立信公司创立的一种无线技术标准，为短距离的硬件设备提供低成本的通信规范。蓝牙规范由蓝牙技术联盟（Bluetooth Special Interest Group，简称SIG）管理，在计算机，手机，传真机，耳机，汽车，家用电器等等很多场景广泛使用。蓝牙具有以下一些特点   免费使用：使用的工作频段在2.4GHz的工科医（ISM）频段，无需申请许可证。 功耗低：BLE4.0包含了">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508314805462_3727_1508314829406.png">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508314916535_7138_1508314940423.png">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508314941142_8213_1508314965035.png">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508315210401_5391_1508315234216.png">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508315221637_8594_1508315245508.png">
<meta property="og:image" content="https://blog-10039692.file.myqcloud.com/1508315245679_1026_1508315269498.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="小程序蓝牙记录">
<meta name="twitter:description" content="一、背景介绍 蓝牙是爱立信公司创立的一种无线技术标准，为短距离的硬件设备提供低成本的通信规范。蓝牙规范由蓝牙技术联盟（Bluetooth Special Interest Group，简称SIG）管理，在计算机，手机，传真机，耳机，汽车，家用电器等等很多场景广泛使用。蓝牙具有以下一些特点   免费使用：使用的工作频段在2.4GHz的工科医（ISM）频段，无需申请许可证。 功耗低：BLE4.0包含了">
<meta name="twitter:image" content="https://blog-10039692.file.myqcloud.com/1508314805462_3727_1508314829406.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、背景介绍"><span class="toc-text">一、背景介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、小程序蓝牙介绍"><span class="toc-text">二、小程序蓝牙介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-介绍"><span class="toc-text">2.1 介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-API总览"><span class="toc-text">2.2 API总览</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-主要流程"><span class="toc-text">2.3 主要流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-完整例子"><span class="toc-text">2.4 完整例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-跳坑总结"><span class="toc-text">2.5 跳坑总结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、其他知识"><span class="toc-text">三、其他知识</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-weapp-bluetooth" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">小程序蓝牙记录</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.08.31</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 5.4k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 23分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、背景介绍"><a href="#一、背景介绍" class="headerlink" title="一、背景介绍"></a>一、背景介绍</h2><blockquote>
<p>蓝牙是爱立信公司创立的一种无线技术标准，为短距离的硬件设备提供低成本的通信规范。蓝牙规范由蓝牙技术联盟（Bluetooth Special Interest Group，简称SIG）管理，在计算机，手机，传真机，耳机，汽车，家用电器等等很多场景广泛使用。蓝牙具有以下一些特点</p>
</blockquote>
<ul>
<li>免费使用：使用的工作频段在2.4GHz的工科医（ISM）频段，无需申请许可证。</li>
<li>功耗低：BLE4.0包含了一个低功耗标准(Bluetooth Low Energy)，可以让蓝牙的功耗显著降低</li>
<li>安全性高：蓝牙规范提供了一套安全加密机制和授权机制，可以有效防范数据被窃取</li>
<li>传输率高：目前最新BLE4.0版本，理论传输速率可达3Mbit/s(实际肯定达不到)，理论覆盖范围可达100米</li>
</ul>
<h2 id="二、小程序蓝牙介绍"><a href="#二、小程序蓝牙介绍" class="headerlink" title="二、小程序蓝牙介绍"></a>二、小程序蓝牙介绍</h2><h3 id="2-1-介绍"><a href="#2-1-介绍" class="headerlink" title="2.1 介绍"></a>2.1 介绍</h3><blockquote>
<p>小程序API提供了一套蓝牙操作接口，所以作为我们前端开发人员可以更加方便的进行蓝牙设备开发，而无需了解安卓和IOS的各种蓝牙底层概念。小程序的蓝牙操作大多都是通过异步调用来处理的，这里面就存在着一些坑，后面会详细介绍。在使用小程序蓝牙API之前有几个概念或者说术语需要预先了解</p>
</blockquote>
<ul>
<li>蓝牙终端：我们常说的硬件设备，包括手机，电脑等等。</li>
<li>UUID:是由子母和数字组成的40个字符串的序号,根据硬件设备有关联的唯一ID</li>
<li>设备地址：每个蓝牙设备都有一个设备地址deviceId，但是安卓和IOS差别很大，安卓下设备地址就是mac地址，但是IOS无法获取mac地址，所以设备地址是针对本机范围有效的UUID，所以这里需要注意</li>
<li>设备服务列表：每个设备都存在一些服务列表，可以跟不同的设备进行通信，服务有一个serviceId来维护，每个服务包含了一组特征值</li>
<li>服务特征值：包含一个单独的value值和0 –n个用来描述characteristic 值（value）的descriptors。一个characteristics可以被认为是一种类型的，类似于一个类</li>
<li>ArrayBuffer:小程序中对蓝牙数据的传递是使用ArrayBuffer的二进制类型来的，所以在我们的使用过程中需要进行转码</li>
</ul>
<p><img src="https://blog-10039692.file.myqcloud.com/1508314805462_3727_1508314829406.png" alt></p>
<h3 id="2-2-API总览"><a href="#2-2-API总览" class="headerlink" title="2.2 API总览"></a>2.2 API总览</h3><blockquote>
<p>小程序对蓝牙设备的操作有18个API</p>
</blockquote>
<table>
<thead>
<tr>
<th>API名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>openBluetoothAdapter</code></td>
<td>初始化蓝牙适配器，在此可用判断蓝牙是否可用</td>
</tr>
<tr>
<td><code>closeBluetoothAdapter</code></td>
<td>关闭蓝牙连接，释放资源</td>
</tr>
<tr>
<td><code>getBluetoothAdapterState</code></td>
<td>获取蓝牙适配器状态，如果蓝牙未开或不可用，这里可用检测到</td>
</tr>
<tr>
<td><code>onBluetoothAdapterStateChange</code></td>
<td>蓝牙适配器状态发生变化事件，这里可用监控蓝牙的关闭和打开动作</td>
</tr>
<tr>
<td><code>startBluetoothDevicesDiscovery</code></td>
<td>开始搜索设备，蓝牙初始化成功后就可以搜索设备</td>
</tr>
<tr>
<td><code>stopBluetoothDevicesDiscovery</code></td>
<td>当找到目标设备以后需要停止搜索，因为搜索设备是比较消耗资源的操作</td>
</tr>
<tr>
<td><code>getBluetoothDevices</code></td>
<td>获取已经搜索到的设备列表</td>
</tr>
<tr>
<td><code>onBluetoothDeviceFound</code></td>
<td>当搜索到一个设备时的事件，在此可用过滤目标设备</td>
</tr>
<tr>
<td><code>getConnectedBluetoothDevices</code></td>
<td>获取已连接的设备</td>
</tr>
<tr>
<td><code>createBLEConnection</code></td>
<td>创建BLE连接</td>
</tr>
<tr>
<td><code>closeBLEConnection</code></td>
<td>关闭BLE连接</td>
</tr>
<tr>
<td><code>getBLEDeviceServices</code></td>
<td>获取设备的服务列表，每个蓝牙设备都有一些服务</td>
</tr>
<tr>
<td><code>getBLEDeviceCharacteristics</code></td>
<td>获取蓝牙设备某个服务的特征值列表</td>
</tr>
<tr>
<td><code>readBLECharacteristicValue</code></td>
<td>读取低功耗蓝牙设备的特征值的二进制数据值</td>
</tr>
<tr>
<td><code>writeBLECharacteristicValue</code></td>
<td>向蓝牙设备写入数据</td>
</tr>
<tr>
<td><code>notifyBLECharacteristicValueChange</code></td>
<td>开启蓝牙设备<code>notify</code>提醒功能，只有开启这个功能才能接受到蓝牙推送的数据</td>
</tr>
<tr>
<td><code>onBLEConnectionStateChange</code></td>
<td>监听蓝牙设备错误事件，包括异常断开等等</td>
</tr>
<tr>
<td><code>onBLECharacteristicValueChange</code></td>
<td>监听蓝牙推送的数据，也就是<code>notify</code>数据</td>
</tr>
</tbody>
</table>
<h3 id="2-3-主要流程"><a href="#2-3-主要流程" class="headerlink" title="2.3 主要流程"></a>2.3 主要流程</h3><blockquote>
<p>蓝牙通信的一个正常流程是下面的图示</p>
</blockquote>
<p><img src="https://blog-10039692.file.myqcloud.com/1508314916535_7138_1508314940423.png" alt></p>
<ol>
<li>开启蓝牙：调用<code>openBluetoothAdapter</code>来开启和初始化蓝牙，这个时候可以根据状态判断用户设备是否支持蓝牙</li>
<li>检查蓝牙状态：调用<code>getBluetoothAdapterState</code>来检查蓝牙是否开启，如果没有开启可以在这里提醒用户开启蓝牙，并且能在开启后自动启动下面的步骤</li>
</ol>
<blockquote>
<p>这里有一个坑：IOS里面蓝牙状态变化以后不能马上开始搜索，否则会搜索不到设备，必须要等待2秒以上。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  wx.openBluetoothAdapter(&#123;</span><br><span class="line">    success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    &#125;,</span><br><span class="line">    fail(res)&#123;</span><br><span class="line">    &#125;,</span><br><span class="line">    complete(res)&#123;</span><br><span class="line">      wx.onBluetoothAdapterStateChange(<span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(res.available)&#123;</span><br><span class="line">          setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            connect();</span><br><span class="line">          &#125;,<span class="number">2000</span>);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">　　　<span class="comment">//开始搜索  </span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>搜索设备：<code>startBluetoothDevicesDiscovery</code>开始搜索设备，当发现一个设备会触发<code>onBluetoothDeviceFound</code>事件，首先看下标准API</li>
</ol>
<p><img src="https://blog-10039692.file.myqcloud.com/1508314941142_8213_1508314965035.png" alt></p>
<p><strong>由于IOS无法获取Mac地址所以这里需要区分两个场景</strong></p>
<ol>
<li>安卓：安卓下可以根据<code>Mac</code>地址来搜索设备，或者跳过此步直接连接到设备。当搜索到一个设备以后，可以在<code>onBluetoothDeviceFound</code>事件回调中判断当前设备的<code>deviceID</code>是否为指定的<code>Mac</code>地址</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> mac = <span class="string">"XXXXXXXXXXXXXXX"</span>;</span><br><span class="line">wx.startBluetoothDevicesDiscovery(&#123;</span><br><span class="line">  services:[],</span><br><span class="line">  success(res) &#123;</span><br><span class="line">    wx.onBluetoothDeviceFound(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">let</span> devices = res.devices;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i&lt;devices.length;i++)&#123;</span><br><span class="line">          <span class="keyword">if</span>(devices[i].deviceId = mac)&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"find"</span>);</span><br><span class="line">            wx.stopBluetoothDevicesDiscovery(&#123;</span><br><span class="line">              success:<span class="function"><span class="params">res</span>=&gt;</span><span class="built_in">console</span>.log(res),</span><br><span class="line">              fail:<span class="function"><span class="params">res</span>=&gt;</span><span class="built_in">console</span>.log(res),</span><br><span class="line">            &#125;)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(res);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>IOS：IOS下获取设备Mac地址的方法已经被屏蔽，所以不存在mac地址，此时只能通过其他方式来判断，比如在蓝牙设备advertisData字段添加一些特别的信息来判断等等，可以转字符串来判断，也可以直接用二进制来判断</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> id = <span class="string">"XXXXXXXXXXXXXXX"</span>,<span class="comment">//设备标识符</span></span><br><span class="line">    deviceId = <span class="string">""</span>;</span><br><span class="line">wx.startBluetoothDevicesDiscovery(&#123;</span><br><span class="line">  services:[],</span><br><span class="line">  success(res) &#123;</span><br><span class="line">    wx.onBluetoothDeviceFound(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> devices = res.devices;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i&lt;devices.length;i++)&#123;</span><br><span class="line">          <span class="keyword">let</span> advertisData = devices[i].advertisData;</span><br><span class="line">          <span class="keyword">var</span> data = arrayBufferToHexString(advertisData);<span class="comment">//二进制转字符串</span></span><br><span class="line">          <span class="keyword">if</span> (!!data &amp;&amp; data.indexOf(id) &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">              <span class="built_in">console</span>.log(<span class="string">"find"</span>);</span><br><span class="line">　　　　　　　　deviceId = devices[i].deviceId;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);    </span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(res);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">arrayBufferToHexString</span>(<span class="params">buffer</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> bufferType = <span class="built_in">Object</span>.prototype.toString.call(buffer)</span><br><span class="line">  <span class="keyword">if</span> (buffer != <span class="string">'[object ArrayBuffer]'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> dataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buffer)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> hexStr = <span class="string">''</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; dataView.byteLength; i++) &#123;</span><br><span class="line">    <span class="keyword">var</span> str = dataView.getUint8(i);</span><br><span class="line">    <span class="keyword">var</span> hex = (str &amp; <span class="number">0xff</span>).toString(<span class="number">16</span>);</span><br><span class="line">    hex = (hex.length === <span class="number">1</span>) ? <span class="string">'0'</span> + hex : hex;</span><br><span class="line">    hexStr += hex;</span><br><span class="line">  &#125;</span><br><span class="line">****</span><br><span class="line">  <span class="keyword">return</span> hexStr.toUpperCase();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这里需要注意的是：如果知道mac地址在安卓下可以直接略过搜索过程直接连接，如果不知道mac地址或者是IOS场景下需要开启搜索，由于搜索是比较消耗资源的动作，所以发现目标设备以后一定要及时关闭搜索，以节省系统消耗</p>
</blockquote>
<ol start="4">
<li>搜索到设备以后，就是连接设备<code>createBLEConnection</code></li>
<li>连接成功以后就开始查询设备的服务列表：<code>getBLEDeviceServices</code>，然后根据目标服务ID或者标识符来找到指定的服务<code>ID</code></li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> deviceId = <span class="string">"XXXX"</span>;</span><br><span class="line">wx.getBLEDeviceServices(&#123;</span><br><span class="line">  deviceId: device_id,</span><br><span class="line">  success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;        </span><br><span class="line">    <span class="keyword">let</span> service_id = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i&lt;res.services.length;i++)&#123;</span><br><span class="line">      <span class="keyword">if</span>(services[i].uuid.toUpperCase().indexOf(<span class="string">"TEST"</span>) != <span class="number">-1</span>)&#123;</span><br><span class="line">        service_id = services[i].uuid;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> service_id;</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这里有个坑的地方：如果是安卓下如果你知道设备的服务ID，你可以省去<code>getBLEDeviceServices</code>的过程，但是<code>IOS</code>下即使你知道了服务ID，也不能省去<code>getBLEDeviceServices</code>的过程，这是小程序里面需要注意的一点</p>
</blockquote>
<ol start="6">
<li>获取服务特征值：每个服务都包含了一组特征值用来描述服务的一些属性，比如是否可读，是否可写，是否可以开启<code>notify</code>通知等等，当你跟蓝牙通信时需要这些特征值ID来传递数据</li>
</ol>
<blockquote>
<p><code>getBLEDeviceCharacteristics</code>方法返回了res参数包含了以下属性</p>
</blockquote>
<p><img src="https://blog-10039692.file.myqcloud.com/1508315210401_5391_1508315234216.png" alt></p>
<blockquote>
<p><code>characteristics</code>包含了一组特征值列表</p>
</blockquote>
<p><img src="https://blog-10039692.file.myqcloud.com/1508315221637_8594_1508315245508.png" alt></p>
<blockquote>
<p>通过遍历特征值对象来获取想要的特征值ID</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">wx.getBLEDeviceCharacteristics(&#123;</span><br><span class="line">  deviceId: device_id,</span><br><span class="line">  serviceId: service_id,</span><br><span class="line">  success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> notify_id,write_id,read_id;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; res.characteristics.length; i++) &#123;</span><br><span class="line">      <span class="keyword">let</span> charc = res.characteristics[i];</span><br><span class="line">      <span class="keyword">if</span> (charc.properties.notify) &#123;</span><br><span class="line">        notify_id = charc.uuid;           </span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(charc.properties.write)&#123;</span><br><span class="line">        write_id = charc.uuid;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span>(charc.properties.write)&#123;</span><br><span class="line">        read_id = charc.uuid;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res); </span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这个例子就通过搜索特征值取到了 <code>notify</code>特征值<code>ID</code>，写<code>ID</code>和读取<code>ID</code></p>
</blockquote>
<ol start="7">
<li>获取特征值ID以后就可以开启<code>notify</code>通知模式，同时开启监听特征值变化消息</li>
</ol>
<p><img src="https://blog-10039692.file.myqcloud.com/1508315245679_1026_1508315269498.png" alt></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">wx.notifyBLECharacteristicValueChange(&#123;</span><br><span class="line">  state: <span class="literal">true</span>,</span><br><span class="line">  deviceId: device_id,</span><br><span class="line">  serviceId: service_id,</span><br><span class="line">  characteristicId:notify_id,</span><br><span class="line">  complete(res) &#123;</span><br><span class="line">    wx.onBLECharacteristicValueChange(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(arrayBufferToHexString(res.value));</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ol start="8">
<li>一切都准备好以后，就可以开始给蓝牙发送消息，一旦蓝牙有响应，就可以在<code>onBLECharacteristicValueChange</code>事件中得到消息并打印出来</li>
</ol>
<blockquote>
<p>这里面有个坑：开启notify以后并不能马上发送消息，蓝牙设备有个准备的过程，需要在setTimeout中延迟1秒以上才能发送，否则会发送失败</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> buf = hexStringToArrayBuffer(<span class="string">"test"</span>);</span><br><span class="line">wx.writeBLECharacteristicValue(&#123;</span><br><span class="line">  deviceId: device_id,</span><br><span class="line">  serviceId: service_id,</span><br><span class="line">  characteristicId:write_id,</span><br><span class="line">  value: buf,</span><br><span class="line">  success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(buf);</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hexStringToArrayBuffer</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!str) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(<span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">var</span> buffer = <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(str.length);</span><br><span class="line">  <span class="keyword">let</span> dataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buffer)</span><br><span class="line">  <span class="keyword">let</span> ind = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = str.length; i &lt; len; i += <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> code = <span class="built_in">parseInt</span>(str.substr(i, <span class="number">2</span>), <span class="number">16</span>)</span><br><span class="line">    dataView.setUint8(ind, code)</span><br><span class="line">    ind++</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> buffer;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="9">
<li>所有都通信完毕后可以断开连接:</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">wx.closeBLEConnection(&#123;</span><br><span class="line">  deviceId: device_id,</span><br><span class="line">  success(res) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res)</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">wx.closeBluetoothAdapter(&#123;</span><br><span class="line">  success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="2-4-完整例子"><a href="#2-4-完整例子" class="headerlink" title="2.4 完整例子"></a>2.4 完整例子</h3><p><strong>例子1</strong></p>
<blockquote>
<p>这里为了简洁，把fail等异常处理已经省去，主要流程就是设置设备ID和服务ID的过滤值，在开启notify之后写入测试消息，然后监听蓝牙发送过来的消息，整个过程采用简化处理，没有使用事件通信来驱动，仅做参考</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> blueApi = &#123;</span><br><span class="line">  cfg:&#123;</span><br><span class="line">    device_info:<span class="string">"AAA"</span>,</span><br><span class="line">    server_info:<span class="string">"BBB"</span>,</span><br><span class="line">    onOpenNotify:<span class="literal">null</span></span><br><span class="line">  &#125;,</span><br><span class="line">  blue_data:&#123;</span><br><span class="line">    device_id:<span class="string">""</span>,</span><br><span class="line">    service_id:<span class="string">""</span>,</span><br><span class="line">    write_id:<span class="string">""</span></span><br><span class="line">  &#125;,</span><br><span class="line">  setCfg(obj)&#123;</span><br><span class="line">    <span class="keyword">this</span>.cfg = <span class="built_in">Object</span>.assign(&#123;&#125;,<span class="keyword">this</span>.cfg,obj);</span><br><span class="line">  &#125;,</span><br><span class="line">  connect()&#123;</span><br><span class="line">    <span class="keyword">if</span>(!wx.openBluetoothAdapter)&#123;</span><br><span class="line">      <span class="keyword">this</span>.showError(<span class="string">"当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"</span>);</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.openBluetoothAdapter(&#123;</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">      &#125;,</span><br><span class="line">      complete(res)&#123;</span><br><span class="line">        wx.onBluetoothAdapterStateChange(<span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">if</span>(res.available)&#123;</span><br><span class="line">            setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">              _this.connect();</span><br><span class="line">            &#125;,<span class="number">2000</span>);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        _this.getBlueState();        </span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//发送消息</span></span><br><span class="line">  sendMsg(msg,toArrayBuf = <span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    <span class="keyword">let</span> buf = toArrayBuf ? <span class="keyword">this</span>.hexStringToArrayBuffer(msg) : msg;</span><br><span class="line">    wx.writeBLECharacteristicValue(&#123;</span><br><span class="line">      deviceId: _this.blue_data.device_id,</span><br><span class="line">      serviceId: _this.blue_data.service_id,</span><br><span class="line">      characteristicId:_this.blue_data.write_id,</span><br><span class="line">      value: buf,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//监听消息</span></span><br><span class="line">  onNotifyChange(callback)&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.onBLECharacteristicValueChange(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> msg = _this.arrayBufferToHexString(res.value);</span><br><span class="line">      callback &amp;&amp; callback(msg);</span><br><span class="line">      <span class="built_in">console</span>.log(msg);</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  disconnect()&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.closeBLEConnection(&#123;</span><br><span class="line">      deviceId: _this.blue_data.device_id,</span><br><span class="line">      success(res) &#123;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">/*事件通信模块*/</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/*连接设备模块*/</span></span><br><span class="line">  getBlueState() &#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    <span class="keyword">if</span>(_this.blue_data.device_id != <span class="string">""</span>)&#123;</span><br><span class="line">      _this.connectDevice();</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    wx.getBluetoothAdapterState(&#123;</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!!res &amp;&amp; res.available) &#123;<span class="comment">//蓝牙可用    </span></span><br><span class="line">          _this.startSearch();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  startSearch()&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.startBluetoothDevicesDiscovery(&#123;</span><br><span class="line">      services:[],</span><br><span class="line">      success(res) &#123;</span><br><span class="line">        wx.onBluetoothDeviceFound(<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">          <span class="keyword">var</span> device = _this.filterDevice(res.devices);</span><br><span class="line">          <span class="keyword">if</span>(device)&#123;</span><br><span class="line">            _this.blue_data.device_id = device.deviceId;</span><br><span class="line">            _this.stopSearch();</span><br><span class="line">            _this.connectDevice();</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//连接到设备</span></span><br><span class="line">  connectDevice()&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.createBLEConnection(&#123;</span><br><span class="line">      deviceId: _this.blue_data.device_id,</span><br><span class="line">      success(res) &#123;</span><br><span class="line">        _this.getDeviceService();</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;, </span><br><span class="line">  <span class="comment">//搜索设备服务</span></span><br><span class="line">  getDeviceService()&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.getBLEDeviceServices(&#123;</span><br><span class="line">      deviceId: _this.blue_data.device_id,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> service_id = _this.filterService(res.services);</span><br><span class="line">        <span class="keyword">if</span>(service_id != <span class="string">""</span>)&#123;</span><br><span class="line">          _this.blue_data.service_id = service_id;</span><br><span class="line">          _this.getDeviceCharacter();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//获取连接设备的所有特征值  </span></span><br><span class="line">  getDeviceCharacter() &#123;</span><br><span class="line">    <span class="keyword">let</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.getBLEDeviceCharacteristics(&#123;</span><br><span class="line">      deviceId: _this.blue_data.device_id,</span><br><span class="line">      serviceId: _this.blue_data.service_id,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> notify_id,write_id,read_id;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; res.characteristics.length; i++) &#123;</span><br><span class="line">          <span class="keyword">let</span> charc = res.characteristics[i];</span><br><span class="line">          <span class="keyword">if</span> (charc.properties.notify) &#123;</span><br><span class="line">            notify_id = charc.uuid;           </span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span>(charc.properties.write)&#123;</span><br><span class="line">            write_id = charc.uuid;</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span>(charc.properties.write)&#123;</span><br><span class="line">            read_id = charc.uuid;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;          </span><br><span class="line">        <span class="keyword">if</span>(notify_id != <span class="literal">null</span> &amp;&amp; write_id != <span class="literal">null</span>)&#123;</span><br><span class="line">          _this.blue_data.notify_id = notify_id;</span><br><span class="line">          _this.blue_data.write_id = write_id;</span><br><span class="line">          _this.blue_data.read_id = read_id;</span><br><span class="line"></span><br><span class="line">          _this.openNotify();</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  openNotify()&#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.notifyBLECharacteristicValueChange(&#123;</span><br><span class="line">        state: <span class="literal">true</span>,</span><br><span class="line">        deviceId: _this.blue_data.device_id,</span><br><span class="line">        serviceId: _this.blue_data.service_id,</span><br><span class="line">        characteristicId: _this.blue_data.notify_id,</span><br><span class="line">        complete(res) &#123;</span><br><span class="line">          setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            _this.onOpenNotify &amp;&amp; _this.onOpenNotify();</span><br><span class="line">          &#125;,<span class="number">1000</span>);</span><br><span class="line">          _this.onNotifyChange();<span class="comment">//接受消息</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">/*连接设备模块*/</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">/*其他辅助模块*/</span></span><br><span class="line">  <span class="comment">//停止搜索周边设备  </span></span><br><span class="line">  stopSearch() &#123;</span><br><span class="line">    <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">    wx.stopBluetoothDevicesDiscovery(&#123;</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,  </span><br><span class="line">  arrayBufferToHexString(buffer) &#123;</span><br><span class="line">    <span class="keyword">let</span> bufferType = <span class="built_in">Object</span>.prototype.toString.call(buffer)</span><br><span class="line">    <span class="keyword">if</span> (buffer != <span class="string">'[object ArrayBuffer]'</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> dataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buffer)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> hexStr = <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; dataView.byteLength; i++) &#123;</span><br><span class="line">      <span class="keyword">var</span> str = dataView.getUint8(i);</span><br><span class="line">      <span class="keyword">var</span> hex = (str &amp; <span class="number">0xff</span>).toString(<span class="number">16</span>);</span><br><span class="line">      hex = (hex.length === <span class="number">1</span>) ? <span class="string">'0'</span> + hex : hex;</span><br><span class="line">      hexStr += hex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> hexStr.toUpperCase();</span><br><span class="line">  &#125;,</span><br><span class="line">  hexStringToArrayBuffer(str) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!str) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> buffer = <span class="keyword">new</span> <span class="built_in">ArrayBuffer</span>(str.length);</span><br><span class="line">    <span class="keyword">let</span> dataView = <span class="keyword">new</span> <span class="built_in">DataView</span>(buffer)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> ind = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = str.length; i &lt; len; i += <span class="number">2</span>) &#123;</span><br><span class="line">      <span class="keyword">let</span> code = <span class="built_in">parseInt</span>(str.substr(i, <span class="number">2</span>), <span class="number">16</span>)</span><br><span class="line">      dataView.setUint8(ind, code)</span><br><span class="line">      ind++</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> buffer;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//过滤目标设备</span></span><br><span class="line">  filterDevice(device)&#123;</span><br><span class="line">    <span class="keyword">var</span> data = blueApi.arrayBufferToHexString(device.advertisData);</span><br><span class="line">    <span class="keyword">if</span> (data &amp;&amp; data.indexOf(<span class="keyword">this</span>.device_info.substr(<span class="number">4</span>).toUpperCase()) &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="keyword">var</span> obj = &#123; <span class="attr">name</span>: device.name, <span class="attr">deviceId</span>: device.deviceId &#125;</span><br><span class="line">        <span class="keyword">return</span> obj</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">//过滤主服务</span></span><br><span class="line">  filterService(services)&#123;</span><br><span class="line">    <span class="keyword">let</span> service_id = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i&lt;services.length;i++)&#123;</span><br><span class="line">      <span class="keyword">if</span>(services[i].uuid.toUpperCase().indexOf(<span class="keyword">this</span>.server_info) != <span class="number">-1</span>)&#123;</span><br><span class="line">        service_id = services[i].uuid;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> service_id;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">/*其他辅助模块*/</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">blueApi.setCfg(&#123;  </span><br><span class="line">    device_info:<span class="string">"AAA"</span>,</span><br><span class="line">    server_info:<span class="string">"BBB"</span>,</span><br><span class="line">    onOpenNotify:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      blueApi.sendMsg(<span class="string">"test"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">blueApi.connect();</span><br><span class="line">blueApi.onNotifyChange(<span class="function"><span class="keyword">function</span>(<span class="params">msg</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(msg);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><strong>例子2</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> app = getApp()</span><br><span class="line">Page(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line">    searching: <span class="literal">false</span>,</span><br><span class="line">    devicesList: []</span><br><span class="line">  &#125;,</span><br><span class="line">  Search: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> that = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (!that.data.searching) &#123;</span><br><span class="line">      wx.closeBluetoothAdapter(&#123;</span><br><span class="line">        complete: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">          <span class="built_in">console</span>.log(res)</span><br><span class="line">          wx.openBluetoothAdapter(&#123;</span><br><span class="line">            success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">              <span class="built_in">console</span>.log(res)</span><br><span class="line">              wx.getBluetoothAdapterState(&#123;</span><br><span class="line">                success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">                  <span class="built_in">console</span>.log(res)</span><br><span class="line">                &#125;</span><br><span class="line">              &#125;)</span><br><span class="line">              wx.startBluetoothDevicesDiscovery(&#123;</span><br><span class="line">                allowDuplicatesKey: <span class="literal">false</span>,</span><br><span class="line">                success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">                  <span class="built_in">console</span>.log(res)</span><br><span class="line">                  that.setData(&#123;</span><br><span class="line">                    searching: <span class="literal">true</span>,</span><br><span class="line">                    devicesList: []</span><br><span class="line">                  &#125;)</span><br><span class="line">                &#125;</span><br><span class="line">              &#125;)</span><br><span class="line">            &#125;,</span><br><span class="line">            fail: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">              <span class="built_in">console</span>.log(res)</span><br><span class="line">              wx.showModal(&#123;</span><br><span class="line">                title: <span class="string">'提示'</span>,</span><br><span class="line">                content: <span class="string">'请检查手机蓝牙是否打开'</span>,</span><br><span class="line">                showCancel: <span class="literal">false</span>,</span><br><span class="line">                success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">                  that.setData(&#123;</span><br><span class="line">                    searching: <span class="literal">false</span></span><br><span class="line">                  &#125;)</span><br><span class="line">                &#125;</span><br><span class="line">              &#125;)</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">      wx.stopBluetoothDevicesDiscovery(&#123;</span><br><span class="line">        success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">          <span class="built_in">console</span>.log(res)</span><br><span class="line">          that.setData(&#123;</span><br><span class="line">            searching: <span class="literal">false</span></span><br><span class="line">          &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  Connect: <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> that = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">var</span> advertisData, name</span><br><span class="line">    <span class="built_in">console</span>.log(e.currentTarget.id)</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; that.data.devicesList.length; i++) &#123;</span><br><span class="line">      <span class="keyword">if</span> (e.currentTarget.id == that.data.devicesList[i].deviceId) &#123;</span><br><span class="line">        name = that.data.devicesList[i].name</span><br><span class="line">        advertisData = that.data.devicesList[i].advertisData</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    wx.stopBluetoothDevicesDiscovery(&#123;</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        that.setData(&#123;</span><br><span class="line">          searching: <span class="literal">false</span></span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    wx.showLoading(&#123;</span><br><span class="line">      title: <span class="string">'连接蓝牙设备中...'</span>,</span><br><span class="line">    &#125;)</span><br><span class="line">    wx.createBLEConnection(&#123;</span><br><span class="line">      deviceId: e.currentTarget.id,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        wx.hideLoading()</span><br><span class="line">        wx.showToast(&#123;</span><br><span class="line">          title: <span class="string">'连接成功'</span>,</span><br><span class="line">          icon: <span class="string">'success'</span>,</span><br><span class="line">          duration: <span class="number">1000</span></span><br><span class="line">        &#125;)</span><br><span class="line">        wx.navigateTo(&#123;</span><br><span class="line">          url: <span class="string">'../device/device?connectedDeviceId='</span> + e.currentTarget.id + <span class="string">'&amp;name='</span> + name</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        wx.hideLoading()</span><br><span class="line">        wx.showModal(&#123;</span><br><span class="line">          title: <span class="string">'提示'</span>,</span><br><span class="line">          content: <span class="string">'连接失败'</span>,</span><br><span class="line">          showCancel: <span class="literal">false</span></span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  onLoad: <span class="function"><span class="keyword">function</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> that = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">var</span> list_height = ((app.globalData.SystemInfo.windowHeight - <span class="number">50</span>) * (<span class="number">750</span> / app.globalData.SystemInfo.windowWidth)) - <span class="number">60</span></span><br><span class="line">    that.setData(&#123;</span><br><span class="line">      list_height: list_height</span><br><span class="line">    &#125;)</span><br><span class="line">    wx.onBluetoothAdapterStateChange(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(res)</span><br><span class="line">      that.setData(&#123;</span><br><span class="line">        searching: res.discovering</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">if</span> (!res.available) &#123;</span><br><span class="line">        that.setData(&#123;</span><br><span class="line">          searching: <span class="literal">false</span></span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    wx.onBluetoothDeviceFound(<span class="function"><span class="keyword">function</span> (<span class="params">devices</span>) </span>&#123;</span><br><span class="line">      <span class="comment">//剔除重复设备，兼容不同设备API的不同返回值</span></span><br><span class="line">      <span class="keyword">var</span> isnotexist = <span class="literal">true</span></span><br><span class="line">      <span class="keyword">if</span> (devices.deviceId) &#123;</span><br><span class="line">        <span class="keyword">if</span> (devices.advertisData)</span><br><span class="line">        &#123;</span><br><span class="line">          devices.advertisData = app.buf2hex(devices.advertisData)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">          devices.advertisData = <span class="string">''</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(devices)</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; that.data.devicesList.length; i++) &#123;</span><br><span class="line">          <span class="keyword">if</span> (devices.deviceId == that.data.devicesList[i].deviceId) &#123;</span><br><span class="line">            isnotexist = <span class="literal">false</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (isnotexist) &#123;</span><br><span class="line">          that.data.devicesList.push(devices)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (devices.devices) &#123;</span><br><span class="line">        <span class="keyword">if</span> (devices.devices[<span class="number">0</span>].advertisData)</span><br><span class="line">        &#123;</span><br><span class="line">          devices.devices[<span class="number">0</span>].advertisData = app.buf2hex(devices.devices[<span class="number">0</span>].advertisData)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">          devices.devices[<span class="number">0</span>].advertisData = <span class="string">''</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(devices.devices[<span class="number">0</span>])</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; that.data.devicesList.length; i++) &#123;</span><br><span class="line">          <span class="keyword">if</span> (devices.devices[<span class="number">0</span>].deviceId == that.data.devicesList[i].deviceId) &#123;</span><br><span class="line">            isnotexist = <span class="literal">false</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (isnotexist) &#123;</span><br><span class="line">          that.data.devicesList.push(devices.devices[<span class="number">0</span>])</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (devices[<span class="number">0</span>]) &#123;</span><br><span class="line">        <span class="keyword">if</span> (devices[<span class="number">0</span>].advertisData)</span><br><span class="line">        &#123;</span><br><span class="line">          devices[<span class="number">0</span>].advertisData = app.buf2hex(devices[<span class="number">0</span>].advertisData)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">          devices[<span class="number">0</span>].advertisData = <span class="string">''</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(devices[<span class="number">0</span>])</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; devices_list.length; i++) &#123;</span><br><span class="line">          <span class="keyword">if</span> (devices[<span class="number">0</span>].deviceId == that.data.devicesList[i].deviceId) &#123;</span><br><span class="line">            isnotexist = <span class="literal">false</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (isnotexist) &#123;</span><br><span class="line">          that.data.devicesList.push(devices[<span class="number">0</span>])</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      that.setData(&#123;</span><br><span class="line">        devicesList: that.data.devicesList</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line">  onReady: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br><span class="line">  onShow: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    </span><br><span class="line">  &#125;,</span><br><span class="line">  onHide: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> that = <span class="keyword">this</span></span><br><span class="line">    that.setData(&#123;</span><br><span class="line">      devicesList: []</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.data.searching) &#123;</span><br><span class="line">      wx.stopBluetoothDevicesDiscovery(&#123;</span><br><span class="line">        success: <span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">          <span class="built_in">console</span>.log(res)</span><br><span class="line">          that.setData(&#123;</span><br><span class="line">            searching: <span class="literal">false</span></span><br><span class="line">          &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="2-5-跳坑总结"><a href="#2-5-跳坑总结" class="headerlink" title="2.5 跳坑总结"></a>2.5 跳坑总结</h3><p><strong>1. 等待响应：很多情况下需要等待设备响应，尤其在IOS环境下，比如</strong></p>
<ul>
<li>监听到蓝牙开启后，不能马上开始搜索，需要等待2秒</li>
<li>开启notify以后，不能马上发送消息，需要等待1秒</li>
</ul>
<p><strong>2. Mac和UUID</strong></p>
<blockquote>
<p>安卓的mac地址是可以获取到的所以设备的ID是固定的，但是IOS是获取不到MAC地址的，只能获取设备的UUID，而且是动态的，所以需要使用其他方法来查询</p>
</blockquote>
<p><strong>3. IOS下只有搜索可以省略</strong></p>
<blockquote>
<p>如果你知道了设备的ID，服务ID和各种特征值ID，在安卓下可以直接连接，然后发送消息，省去搜索设备，搜索服务和搜索特征值的过程，但是在IOS下，只能指定设备ID连接，后面的过程是不能省略的。</p>
</blockquote>
<p><strong>4. 监听到的消息要进行过滤处理</strong></p>
<blockquote>
<p>有些设备会抽风一样的发送同样的消息，需要在处理逻辑里面去重。</p>
</blockquote>
<p><strong>5.  操作完成后要及时关闭连接</strong></p>
<blockquote>
<p>同时也要关闭蓝牙设备，否则安卓下再次进入会搜索不到设备除非关闭小程序进程再进才可以，IOS不受影响。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">wx.closeBLEConnection(&#123;</span><br><span class="line">  deviceId: _this.blue_data.device_id,</span><br><span class="line">  success(res) &#123;</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res) &#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">wx.closeBluetoothAdapter(&#123;</span><br><span class="line">  success(res)&#123;</span><br><span class="line">  &#125;,</span><br><span class="line">  fail(res)&#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>除了以上的常见问题，你还需要处理很多异常情况，比如蓝牙中途关闭，网络断开，GPS未开启等等场景，总之和硬件设备打交道跟纯UI交互还是有很大的差别的</p>
</blockquote>
<h2 id="三、其他知识"><a href="#三、其他知识" class="headerlink" title="三、其他知识"></a>三、其他知识</h2><p><strong>硬件字节</strong></p>
<blockquote>
<p><strong>ArrayBuffer</strong>：类型化数组，JavaScript操作二进制数据的一个接口。 WebGL，指浏览器与显卡之间的通信接口，为了满足JavaScript与显卡之间大量的、实时的数据交换，它们之间的数据通信必须是二进制的，而不能是传统的文本格式。 比如，以文本格式传递一个32位整数，两端的JavaScript脚本与显卡都要进行格式转化，将非常耗时。这时要是存在一种机制，可以像C语言那样，直接操作字节，然后将4个字节的32位整数，以二进制形式原封不动地送入显卡，脚本的性能就会大幅提升。 类型化数组（Typed Array）就是在这种背景下诞生的。它很像C语言的数组，允许开发者以数组下标的形式，直接操作内存。有了类型化数组以后，JavaScript的二进制数据处理功能增强了很多，接口之间完全可以用二进制数据通信</p>
</blockquote>
<blockquote>
<p><code>ArrayBuffer</code>作为内存区域，可以存放多种类型的数据。不同数据有不同的存储方式，这就叫做“视图”。目前，JavaScript提供以下类型的视图：</p>
</blockquote>
<ul>
<li><code>Int8Array</code>：8位有符号整数，长度1个字节。</li>
<li><code>Uint8Array</code>：8位无符号整数，长度1个字节。</li>
<li><code>Int16Array</code>：16位有符号整数，长度2个字节。</li>
<li><code>Uint16Array</code>：16位无符号整数，长度2个字节。</li>
<li><code>Int32Array</code>：32位有符号整数，长度4个字节。</li>
<li><code>Uint32Array</code>：32位无符号整数，长度4个字节。</li>
<li><code>Float32Array</code>：32位浮点数，长度4个字节。</li>
<li><code>Float64Array</code>：64位浮点数，长度8个字</li>
</ul>
<p><strong>客户端要产生一个唯一的标识符：deviceId、MAC地址、AndroidId：</strong></p>
<p><strong>AndroidId</strong></p>
<blockquote>
<p>获取AndroidId是不需要权限的但是AndroidId是可能变的，AndroidId是在用户第一次激活这个设备时产生的所以当用户重置手机时AndroidId会产生变化，理论上这个AndroidId是可以接受的毕竟重置手机这个事发生也不会太频繁</p>
</blockquote>
<p><strong>MAC地址：</strong></p>
<blockquote>
<p>可以使用WIFI的MAC地址来作为标识符，感觉现阶段这种方式比较可靠总结如下：Mac地址是唯一的，直接产生在硬件上基本上不会变更；</p>
</blockquote>
<p><strong>DeviceId</strong></p>
<blockquote>
<p>区别设备唯一设备ID。</p>
</blockquote>
<p><strong>其他</strong></p>
<ol>
<li>profile</li>
</ol>
<blockquote>
<p>profile可以理解为一种规范，一个标准的通信协议，它存在于从机中。蓝牙组织规定了一些标准的profile，例如 HID OVER GATT ，防丢器 ，心率计等。每个profile中会包含多个service，每个service代表从机的一种能力。蓝牙设备可以包括多个Profile，一个Profile中有多个Service，</p>
</blockquote>
<ol start="2">
<li>service服务</li>
</ol>
<blockquote>
<p>service可以理解为一个服务，在ble从机中，通过有多个服务，例如电量信息服务、系统信息服务等，每个service中又包含多个characteristic特征值。每个具体的characteristic特征值才是ble通信的主题。比如当前的电量是80%，所以会通过电量的characteristic特征值存在从机的profile里，这样主机就可以通过这个characteristic来读取80%这个数据；一个Service中有多个Characteristic</p>
</blockquote>
<ol start="3">
<li>characteristic特征</li>
</ol>
<blockquote>
<p>characteristic特征值，例如：read、notify、write等特征…；ble主从机的通信均是通过characteristic的read、write来实现，可以 理解为一个标签，通过这个标签可以获取或者写入想要的内容</p>
</blockquote>
<ol start="4">
<li>UUID</li>
</ol>
<ul>
<li>UUID，统一识别码，我们刚才提到的service和characteristic，都需要一个唯一的uuid来标识</li>
<li>每个从机都会有一个叫做profile的东西存在，不管是上面的自定义的simpleprofile，还是标准的防丢器profile，他们都是由一些列service组成，然后每个service又包含了多个characteristic，主机和从机之间的通信，均是通过characteristic来实现。</li>
<li>实际产品中，每个蓝牙4.0的设备都是通过服务和特征来展示自己的，服务和特征都是用UUID来唯一标识的。一个设备必然包含一个或多个服务，每个服务下面又包含若干个特征。特征是与外界交互的最小单位。蓝牙设备硬件厂商通常都会提供他们的设备里面各个服务(service)和特征(characteristics)的功能，比如哪些是用来交互(读写)，哪些可获取模块信息(只读)等。比如说，一台蓝牙4.0设备，用特征A来描述自己的出厂信息，用特征B来与收发数据等。</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/08/10/react-good-practice/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/08/31/taro-echarts/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
